package com.zxw.auth.handler;

import com.zxw.common.api.ApiResult;
import com.zxw.common.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@Slf4j
public class FailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException e) throws IOException, ServletException {
        ApiResult<String> apiResult = resolveException(e);
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
        PrintWriter printWriter = response.getWriter();
        printWriter.append(new ObjectMapper().writeValueAsString(apiResult));
    }

    private ApiResult<String> resolveException(AuthenticationException e) {
        if (e instanceof LockedException) {
            return ApiResult.failed(ResultCode.LOCKED_EXCEPTION);
        } else if (e instanceof CredentialsExpiredException) {
            return ApiResult.failed(ResultCode.CREDENTIALS_EXPIRED_EXCEPTION);
        } else if (e instanceof AccountExpiredException) {
            return ApiResult.failed(ResultCode.ACCOUNT_EXPIRED_EXCEPTION);
        } else if (e instanceof DisabledException) {
            return ApiResult.failed(ResultCode.DISABLED_EXCEPTION);
        } else if (e instanceof BadCredentialsException) {
            return ApiResult.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR);
        } else if (e instanceof AuthenticationServiceException) {
            return ApiResult.failed(ResultCode.FAILED);
        }
        return ApiResult.failed(ResultCode.FAILED);
    }

}
